
package com.joysuch.wwyt.datadump.biz.convertor;

import cn.zlg.common.datadump.annotation.DataDumpField;
import cn.zlg.common.datadump.convertor.FieldValueConvert;
import cn.zlg.common.datadump.util.QueryDslUtils;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.SimpleExpression;
import com.querydsl.jpa.JPAQueryBase;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 从DataDumpField的referenceEntity，及referenceEntityField中递归查询父项目的属性。<br>
 * 使用exportConvertorParameters, 第一个参数为最终取值的属性名称，第2个属性为层级深度, 如果为空，默认值为1
 * 
 * @since
 *
 */
@Component
public class ExportRecusiveGetParentPropConvertor implements FieldValueConvert<Long, Object> {

    private static final Logger logger = LoggerFactory.getLogger(ExportRecusiveGetParentPropConvertor.class);

    @Autowired
    private JPAQueryFactory queryFactory;

    @Override
    public Object convert(Object bean, Long value, DataDumpField dataField) {
        if (value == null) {
            return null;
        }
        String[] params = dataField.exportConvertorParams();
        if (params.length == 0 || params.length > 2) {
            logger.warn("递归取值配置: exportConvertorParams()参数值为{}, 长度不为1或者2");
            return null;
        }
        String valueProp = params[0];
        Integer level = params.length == 1 ? 1 : Integer.valueOf(params[1]);
        Long parentId = value;
        EntityPathBase entity;
        try {
            entity = QueryDslUtils.findQEntityInstance(dataField.referenceEntity());
            Path parentIdPath = QueryDslUtils.findQPath(dataField.referenceEntity(), dataField.referenceEntityField());
            Path valuePropPath = QueryDslUtils.findQPath(dataField.referenceEntity(), valueProp);
            SimpleExpression entityIdPath = (SimpleExpression) QueryDslUtils.findQPath(dataField.referenceEntity(),
                    dataField.referenceEntityIdField());
            for (int i = 1; i < level; i++) {
                // 查询 level - 1 次父ID
                JPAQueryBase query = queryFactory.select(parentIdPath).from(entity);
                query.where(entityIdPath.eq(parentId));
                parentId = (Long) query.fetchFirst();
                if (parentId == null) {
                    return null;
                }
            }
            JPAQueryBase query = queryFactory.select(valuePropPath).from(entity);
            query.where(entityIdPath.eq(parentId));
            return query.fetchFirst();
        } catch (Exception e) {
            logger.error("递归取值配置转换出错,{}.{} idField={}, initialValue={}", dataField.referenceEntity().getName(),
                    dataField.referenceEntityField(), dataField.referenceEntityIdField(), value, e);
        }
        return null;
    }

}
